<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所在地区" prop="regionId">
        <el-select v-model="queryParams.regionId" placeholder="请选择所在地区" @change="handleRegionChange">
          <el-option
            v-for="item in regions"
            :key="item.regionId + 'region'"
            :label="item.name"
            :value="item.regionId"
            @keyup.enter.native="handleQuery"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属小区" prop="villageId">
        <el-select v-model="queryParams.villageId" placeholder="请选择所属小区" @change="handleVillageChange">
          <el-option
            v-for="item in villages"
            :key="item.villageId + 'village'"
            :label="item.name"
            :value="item.villageId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属楼栋" prop="buildingId">
        <el-select v-model="queryParams.buildingId" placeholder="请选择所属楼栋" @change="handleBuildingChange">
          <el-option
            v-for="item in buildings"
            :key="item.buildingId + 'building'"
            :label="item.name"
            :value="item.buildingId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属单元" prop="unitId">
        <el-select v-model="queryParams.unitId" placeholder="请选择所属小区">
          <el-option
            v-for="item in units"
            :key="item.unitId + 'unit'"
            :label="item.name"
            :value="item.unitId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="房屋名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:house:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:house:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:house:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['business:house:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="houseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="房屋ID" align="center" prop="houseId" />
      <el-table-column label="房屋名称" align="center" prop="name" />
      <el-table-column label="所在地区" align="center" prop="regionId">
        <template slot-scope="scope">
          {{Lookup.getLabel(scope.row.regionId, regions, 'regionId', 'name')}}
        </template>
      </el-table-column>
      <el-table-column label="所属小区" align="center" prop="villageId">
        <template slot-scope="scope">
          {{Lookup.getLabel(scope.row.villageId, villages, 'villageId', 'name')}}
        </template>
      </el-table-column>
      <el-table-column label="所属楼栋" align="center" prop="buildingName" />
      <el-table-column label="所属单元" align="center" prop="unitName" />
      <el-table-column label="房屋编码" align="center" prop="code" />
      <el-table-column label="业主名字" align="center" prop="owner" />
      <el-table-column label="居住人数" align="center" prop="peopleAmount" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:house:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:house:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改房屋对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所在地区" prop="regionId">
          <el-select v-model="form.regionId" placeholder="请选择所在地区" @change="handleRegionChange">
            <el-option
              v-for="item in regions"
              :key="item.regionId + 'regionId'"
              :label="item.name"
              :value="item.regionId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属小区" prop="villageId">
          <el-select :disabled='!form.regionId' v-model="form.villageId" placeholder="请选择所属小区" @change="handleVillageChange">
            <el-option
              v-for="item in villages"
              :key="item.villageId + 'villageId'"
              :label="item.name"
              :value="item.villageId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属楼栋" prop="buildingId">
          <el-select :disabled='!form.villageId' v-model="form.buildingId" placeholder="请选择所属楼栋" @change="handleBuildingChange">
            <el-option
              v-for="item in buildings"
              :key="item.buildingId + 'buildingId'"
              :label="item.name"
              :value="item.buildingId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属单元" prop="unitId">
          <el-select :disabled='!form.villageId' v-model="form.unitId" placeholder="请选择所属单元">
            <el-option
              v-for="item in units"
              :key="item.unitId + 'unitsId'"
              :label="item.name"
              :value="item.unitId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房屋名称" prop="name">
          <el-input :disabled="!form.unitId" v-model="form.name" placeholder="请输入房屋名称" />
        </el-form-item>
        <el-form-item label="房屋编码" prop="code">
          <el-input :disabled="!form.unitId" v-model="form.code" placeholder="请输入房屋编码">
            <template v-if="prevCode" slot="prepend">{{prevCode}}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="业主姓名" prop="owner">
          <el-input :disabled="!form.unitId" v-model="form.owner" placeholder="请输入业主姓名" />
        </el-form-item>
        <el-form-item label="居住人数" prop="peopleAmount">
          <el-input :disabled="!form.unitId" v-model="form.peopleAmount" placeholder="请输入居住人数" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listHouse, getHouse, delHouse, addHouse, updateHouse, exportHouse } from "@/api/business/house";
import Lookup from "../../../utils/business_data_lookup";

export default {
  name: "House",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 房屋表格数据
      houseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        unitId: null,
        regionId: null,
        villageId: null,
        buildingId: null,
        name: null,
        code: null,
        peopleAmount: null,
        owner: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        regionId: [
          { required: true, message: "请选择所在地区", trigger: "blur" }
        ],
        villageId: [
          { required: true, message: "请选择所属小区", trigger: "blur" }
        ],
        buildingId: [
          { required: true, message: "请选择所属楼栋", trigger: "blur" }
        ],
        unitId: [
          { required: true, message: "请选择所属单元", trigger: "blur" }
        ],
        name: [
          {
            required: true, message: '请输入楼栋名称', trigger: "blur"
          }
        ],
        code: [
          {
            required: true, message: '请输入楼栋编码', trigger: "blur"
          }
        ],
      },
      Lookup,
      regions: [],
      villages: [],
      buildings: [],
      units: [],

    };
  },
  computed: {
    prevCode() {
      if (this.form.unitId) {
        let item = Lookup.getItem(this.form.unitId, this.units, 'unitId');
        return item ? item.code + '_' : ''
      }
      return '';
    }
  },
  async created() {
    this.regions = await Lookup.getOptions('REGIONS');
    this.villages = await Lookup.getOptions('VILLAGES', {regionId: 1});
    let item = sessionStorage.getItem('user');
    let parse = JSON.parse(item);
    let s = parse.roles.map(item => item.roleKey).join(',');
    if (s.indexOf('property') !== -1) {
      this.user = parse;
      this.queryParams.villageId = parse.villageId;
    }
    this.$nextTick(this.getList)
  },
  methods: {
    /** 查询房屋列表 */
    getList() {
      this.loading = true;
      listHouse(this.queryParams).then(response => {
        this.houseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        houseId: null,
        unitId: null,
        regionId: null,
        villageId: null,
        createBy: null,
        buildingId: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        name: null,
        code: null,
        peopleAmount: null,
        owner: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.houseId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加房屋";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      if (!row.houseId) {
        row = this.houseList.filter(item => item.houseId === this.ids[0])[0];
      }

      this.buildings = await Lookup.getOptions('BUILDINGS', {villageId: row.villageId});
      this.units = await Lookup.getOptions("UNITS", {buildingId: row.buildingId})

      const houseId = row.houseId;
      getHouse(houseId).then(response => {
        this.form = response.data;
        this.form.code = response.data.code.replace(this.prevCode, '')
        this.open = true;
        this.title = "修改房屋";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.code = this.prevCode + this.form.code;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.houseId != null) {
            updateHouse(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHouse(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const houseIds = row.houseId || this.ids;
      this.$modal.confirm('是否确认删除房屋编号为"' + houseIds + '"的数据项？').then(function() {
        return delHouse(houseIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有房屋数据项？').then(() => {
        this.exportLoading = true;
        return exportHouse(queryParams);
      }).then(response => {
        this.$download.name(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    },
    /**
     * 更新小区下拉选项
     * @param val
     * @returns {Promise<void>}
     */
    async handleRegionChange(val) {
      this.form.villageId = null;
      this.villages = await Lookup.getOptions('VILLAGES', {regionId: val});
    },
    /**
     * 更新楼栋下拉选项
     * @param val
     * @returns {Promise<void>}
     */
    async handleVillageChange(val) {
      this.form.buildingId = null;
      this.buildings = await Lookup.getOptions('BUILDINGS', {villageId: val});
    },
    /**
     * 更新单元下拉选项
     * @param val
     * @returns {Promise<void>}
     */
    async handleBuildingChange(val) {
      this.form.unitId = null;
      this.units = await Lookup.getOptions('UNITS', {buildingId: val});
    }
  }
};
</script>
